<?php

namespace common\models;

use Yii;
use common\util\CommonUtil;

/**
 * This is the model class for table "news".
 *
 * @property integer $id
 * @property string $title
 * @property string $content
 * @property string $news_from
 * @property string $tag
 * @property string $author
 * @property integer $news_type_id
 * @property integer $create_at
 * @property integer $update_at
 */
class News extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'news';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title'], 'required'],
            [['news_type_id'], 'required','message'=>'请选择分类'],
            [['content'], 'string'],
            [['news_type_id', 'create_at', 'update_at'], 'integer'],
            [['title'], 'string', 'max' => 80],
            [['news_from'], 'string', 'max' => 100],
            [['tag'], 'string', 'max' => 255],
            [['author'], 'string', 'max' => 30],
        ];
    }
    
    public function beforeSave($insert){
        
        if(parent::beforeSave($insert)){
            
            $time = time();
            if($this->isNewRecord){
                $this->create_at = $time;
                $this->update_at = $time;
            }else{
                $this->update_at = $time;
            }
            
            return true;
        }else{
            return false;
        }
        
    }
    
    //新增 or 保存   事务
    public function saveWithTrans(){
    
        $transaction = Yii::$app->db->beginTransaction();
    
        $errors = [];
        try {
    
            //1.新增NEWS数据
            if(!$this->save()){
                $errors = $this->errors;
                throw new \Exception();
            }
            
            
            //2.新增未有的TAG
            $arr = explode(',', $this->tag);
            $json = '';
            foreach ($arr as $val){
                
                $model4check = Tag::findOne(['name'=>$val]);
                if(empty($model4check)){
                    
                    $pinyin = CommonUtil::getPinyin($val);
                    $model4check2 = Tag::findOne(['pinyin'=>$pinyin]);
                    
                    $model = new Tag();
                    $model->name = $val;
                    if(empty($model4check2)){
                        $model->pinyin = $pinyin;
                    }else{  //有重复的pinyin，则进行随机
                        $model->pinyin = CommonUtil::uuid();
                    }
                    
                    if(!$model->save()){
                        $errors = $model->errors;
                        throw new \Exception();
                    }
                    
                    //JSON格式化
                    $jsonObj = '{"name":"'.$model->name.'","pinyin":"'.$model->pinyin.'"}';
                    if(!empty($json)){
                        $json .= ',';
                    }
                    $json .= $jsonObj;
                    
                }else{
                    
                    //JSON格式化
                    $jsonObj = '{"name":"'.$model4check->name.'","pinyin":"'.$model4check->pinyin.'"}';
                    if(!empty($json)){
                        $json .= ',';
                    }
                    $json .= $jsonObj;
                    
                }
                
            }
            
            $jsonStr = "[{$json}]";
            
            //3.重构News数据中的TAG字段
            $this->tag = $jsonStr;
            if(!$this->save()){
                $errors = $this->errors;
                throw new \Exception();
            }
            
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
        }
        return $errors;
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => '标题',
            'content' => '内容',
            'news_from' => '来源',
            'tag' => '标签',
            'author' => '作者',
            'news_type_id' => '分类',
            'create_at' => '创建时间',
            'update_at' => '修改时间',
        ];
    }
}
